package TwentyFiveDay;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Merge {
    public int[][] merge(int[][] intervals) {
        if (intervals.length == 0) {
            return new int[0][2];
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            public int compare(int[] interval1, int[] interval2) {
                return interval1[0] - interval2[0];
            }
        });
        List<int[]> merged = new ArrayList<int[]>();
        int left = intervals[0][0], right = intervals[0][1];
        for (int i = 0; i < intervals.length - 1; i++) {
            if (intervals[i + 1][0] > right){
                merged.add(new int[]{left, right});
                left = intervals[i + 1][0];
                right = intervals[i + 1][1];
            } else if (intervals[i + 1][1] > right) {
                right = intervals[i + 1][1];
            }
        }
        merged.add(new int[]{left, right});
        return merged.toArray(new int[merged.size()][]);
    }
}
